package com.etc.myblog.biz;

import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.etc.myblog.dao.CommentDao;
import com.etc.myblog.entity.Comment;
import com.etc.myblog.util.SessionFactoryUtil;

public class CommentBiz {
	
	public List<Comment> find() {
		List<Comment> list = new ArrayList<Comment>();
		SqlSession session = SessionFactoryUtil.getSession();
		try {
			CommentDao dao = session.getMapper(CommentDao.class);
			list = dao.find();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			session.close();
		}
		return list;
	}
	
	public Comment findById(int commentId) {
		Comment comment = null;
		SqlSession session = SessionFactoryUtil.getSession();
		try {
			CommentDao dao = session.getMapper(CommentDao.class);
			comment = dao.findById(commentId);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			session.close();
		}
		return comment;
	}
	
	public List<Comment> findByartId(int articleId) {
		List<Comment> list = new ArrayList<Comment>();
		SqlSession session = SessionFactoryUtil.getSession();
		try {
			CommentDao dao = session.getMapper(CommentDao.class);
			list = dao.findByartId(articleId);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			session.close();
		}
		return list;
	}
	
	public int findCountByartId(int articleId) {
		int count = 0;
		SqlSession session = SessionFactoryUtil.getSession();
		try {
			CommentDao dao = session.getMapper(CommentDao.class);
			count = dao.findCountByartId(articleId);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			session.close();
		}
		return count;
	}
	
	public List<Comment> findBypostUserId(int userId) {
		List<Comment> list = new ArrayList<Comment>();
		SqlSession session = SessionFactoryUtil.getSession();
		try {
			CommentDao dao = session.getMapper(CommentDao.class);
			list = dao.findBypostUserId(userId);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			session.close();
		}
		return list;
	}
	
	public void addComment(Comment comment) {
		SqlSession session = SessionFactoryUtil.getSession();
		try {
			CommentDao dao = session.getMapper(CommentDao.class);
			dao.addComment(comment);
			session.commit();
		} catch (Exception e) {
			System.out.println(e.getMessage());
			session.rollback();
		} finally {
			session.close();
		}
	}
	
	public void deleteComment(int commentId) {
		SqlSession session = SessionFactoryUtil.getSession();
		try {
			CommentDao dao = session.getMapper(CommentDao.class);
			dao.deleteComment(commentId);
			session.commit();
		} catch (Exception e) {
			System.out.println(e.getMessage());
			session.rollback();
		} finally {
			session.close();
		}
	}

}
